/*
 * 文件名：SaleRewardController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年3月26日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 * 废弃，使用MarketingReward
 */

package top.infopub.mgr.mkt.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.dto.mkt.MarketingRewardDto;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.domain.MarketingRewardDomain;
import top.infopub.mgr.mkt.domain.SaleRewardAssist;
import top.infopub.mgr.mkt.domain.SaleRewardDomain;
import top.infopub.mgr.mkt.jsonvo.MarketingRewardJsonVo;
import top.infopub.mgr.mkt.service.*;
import top.infopub.mgr.mkt.vo.MarketingRewardVo;
import top.infopub.mgr.mkt.vo.SaleRewardVo;
import top.infopub.mgr.mkt.vo.SetupProVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.*;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 营销奖励申请
 * @author WuZhiyang
 * @version 2020年3月26日
 * @see SaleRewardController
 * @since
 */
@Controller
@RequestMapping("/saleReward")
public class SaleRewardController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private SetupProService setupProService;

    @Autowired
    private DiscloseProService discloseProService;

    @Autowired
    private SaleRewardService saleRewardService;

    @Autowired
    private MarketManageService marketManageService;

    @Autowired
    private MarketingRewardService marketingRewardService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private BidSubsidyService  bidSubsidyService;
    /**
     * 营销奖励申请列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        //获取登录人员信息
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        //查询区域公司列表
        List<OrgInfo> orgInfoList = marketManageService.queryOrgInfoByAuthUserId(vo);
        request.setAttribute("orgInfoList", orgInfoList);
        //查询营销人员列表
        List<StaffInfo> staffInfoList = marketManageService.queryStaffInfoByAuthUserId(vo);
        request.setAttribute("staffInfoList", staffInfoList);
        return "mkt/lay-marketingReward-list";
    }

    /**
     * 营销奖励列表数据
     *
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<MarketingRewardDomain> queryDataByCondition(MarketingRewardVo marketingRewardVo, ParamPage paramPage) {
        Page<MarketingRewardDomain> page = new Page<MarketingRewardDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //处理时间范围
        if (!StringUtils.isEmpty(marketingRewardVo.getDates())) {
            String[] splitTime = marketingRewardVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            try {
                marketingRewardVo.setEndDate(format.parse(splitTime[1]));
                marketingRewardVo.setStartDate(format.parse(splitTime[0]));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        page = marketingRewardService.selectPageByDomainWhere(page, marketingRewardVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询营销奖励申请详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 营销奖励申请Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String queryById(HttpServletRequest request, String id, String proCode){
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id", id);
        MarketingReward mktRed = marketingRewardService.selectByPrimaryKey(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        if (mktRed != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), mktRed.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), mktRed.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(mktRed.getProcessId()) && mktRed.getProcessId().length() > 10) {
                request.setAttribute("processId", mktRed.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(mktRed.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), mktRed.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("proCode", proCode);
        return "mkt/lay-marketingRewards-detail";
    }

    @RequestMapping("/queryDetailById")
    @ResponseBody
    public RspVo queryDetailById(String id) {
        //交底详情
        MarketingRewardJsonVo mktRwdJson = marketingRewardService.queryDetailById(id);
        return RspVo.getSuccessResponse(mktRwdJson);
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //立项审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }

    /**
     * 编辑营销奖励
     * @param request
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(HttpServletRequest request, String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        MarketingRewardJsonVo mktRwdJson = JSON.parseObject(str, MarketingRewardJsonVo.class);
        MarketingRewardDto mktRwdDto = mktRwdJson.getInfo();
        //更新营销奖励-MKT_SALE_REWARD
        MarketingReward mktRwd = new MarketingReward();
        BeanUtils.copyProperties(mktRwdDto, mktRwd);

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(mktRwdJson.getFileAtt()!=null){
            String[] fileAtt = mktRwdJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, mktRwdDto.getProCode(), file);
                attachmentList.add(attachment);
            }
        }

        //调用service进行数据库操作
        RspVo rspVo = marketingRewardService.editDetail(mktRwd, attachmentList, vo, submitType);
        return rspVo;
    }

    /**
     * 营销奖励申请-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<SaleRewardDomain> queryMyCheckDataByCondition(SaleRewardVo saleRewardVo,
                                                               ParamPage paramPage) {
        Page<SaleRewardDomain> page = new Page<SaleRewardDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (saleRewardVo.getEndDate() != null) {
            saleRewardVo.setEndDate(DateUtils.addDays(saleRewardVo.getEndDate(), 1));
        }
        //查询时，中标结束日期增加一天
        if (saleRewardVo.getBondEndDate() != null) {
            saleRewardVo.setBondEndDate(DateUtils.addDays(saleRewardVo.getBondEndDate(), 1));
        }
        saleRewardVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = saleRewardService.selectMyCheckByDomainWhere(page, saleRewardVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 营销奖励申请-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询已立项的记录
        SetupPro setupPro = new SetupPro();
        setupPro.setProcessStatus("9");
        List<SetupPro> setupPros = setupProService.selectByEntityWhere(setupPro);
        request.setAttribute("setupPros", setupPros);
        return "mkt/lay-saleReward-add";
    }

    /**
     * 新增营销奖励申请
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(SaleRewardAssist saleRewardAssist) {

        //营销奖励申请表处理
        saleRewardAssist.setHrDeptId(saleRewardAssist.getHrDeptid());
        saleRewardAssist.setHrOrgId(saleRewardAssist.getHrOrgid());
        saleRewardAssist.setStaffName(saleRewardAssist.getStaffname());
        saleRewardAssist.setHrStaffApplyId(saleRewardAssist.getHrStaffApplyid());
        String proCodeAndCodes = saleRewardAssist.getProCodeAndCodes();
        String[] split = proCodeAndCodes.split("\\_");
        saleRewardAssist.setProCode(split[0]);
        saleRewardAssist.setProName(split[2]);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        saleRewardAssist.setId(id);
        saleRewardAssist.setSgCityId(split[3]);
        saleRewardAssist.setAddBy(vo.getId());
        saleRewardAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("mkt_sale_reward");
        saleRewardAssist.setCodes(code);
        // 处理processId
        saleRewardAssist.setProcessId(IdFactory.getUUIDUpper());
        saleRewardAssist.setProcessStatus("1");//审批中
        saleRewardAssist.setUptBy(vo.getId());
        saleRewardAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //上传附件
        List<SaleRewardAtt> saleRewardAtts = new ArrayList<SaleRewardAtt>();
        //点检表
        String[] fileAtts1 = saleRewardAssist.getFileAtts1();
        if (fileAtts1 != null) {
            for (String file : fileAtts1) {
                SaleRewardAtt saleRewardAtt = createFileAtt(vo, id, file);
                saleRewardAtt.setTypes("01");
                saleRewardAtts.add(saleRewardAtt);
            }
        }
        //招标文件
        String[] fileAtts2 = saleRewardAssist.getFileAtts2();
        if (fileAtts2 != null) {
            for (String file : fileAtts2) {
                SaleRewardAtt saleRewardAtt = createFileAtt(vo, id, file);
                saleRewardAtt.setTypes("02");
                saleRewardAtts.add(saleRewardAtt);
            }
        }
        saleRewardService.saveSaleReward(saleRewardAssist, saleRewardAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "市场管理 -付款申请-营销奖励申请：项目名="
                                                              + saleRewardAssist.getProName(),
            null);
        return RspVo.getSuccessResponse();
    }

    private SaleRewardAtt createFileAtt(AuthorizationVO vo, String rewardId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        SaleRewardAtt fileAtt = new SaleRewardAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setRewardId(rewardId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 根据id查询立项记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getSaleRewardById")
    @ResponseBody
    public Map<String, Object> getSaleRewardById(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String proCodeAndCodes = request.getParameter("proCodeAndCodes");
            String[] split = proCodeAndCodes.split("\\_");
            SetupProVo setupProVo = setupProService.selectById(split[1]);
            //立项中的营销经理
//            StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(setupProVo.getHrStaffMktId());
//            setupProVo.setHrStaffName(staffInfo.getStaffName());
            Map<String, Object> whereMap = Maps.newHashMap();
            whereMap.put("proCode", split[0]);
            whereMap.put("processStatus", "9");
            whereMap.put("orderCondition", "ADD_TIME desc");
            DisclosePro disclosePro = discloseProService.selectByMapWhere(whereMap).get(0);
            if (null == disclosePro.getWidBidDate()) {
                setupProVo.setBondDateDis(null);
            }
            else {
                setupProVo.setBondDateDis(disclosePro.getWidBidDate());
            }
            map.put("setupProVo", setupProVo);
        }
        catch (Exception e) {
            log.error("查询立项记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 上传附件
     * @param request
     * @param
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "saleRewardAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    //营销奖励新增按钮后可选的项目名称
    @RequestMapping("/optionalProjectName")
    @ResponseBody
    public List<ProjectInfo> optionalProjectName()
    {
        List<ProjectInfo> list =  marketManageService.optionalProjectName();
        return list;
    }
    //营销奖励新增按钮后可选的项目名称
    @RequestMapping("/selectProjectById")
    @ResponseBody
    public ProjectInfo selectProjectById(String proCode)
    {
        ProjectInfo projectInfo =  bidSubsidyService.selectProjectById(proCode);
        return projectInfo;
    }
}
